package com.hbmy.workqueue;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeoutException;

import org.apache.commons.lang3.time.DateFormatUtils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

/**
 * <p>
 * 数据持久化<br>
 * 1.队列声明持久化 durable = true; 2.消息持久化 MessageProperties.PERSISTENT_TEXT_PLAIN
 * 
 * </p>
 * 
 * @author Administrator
 *
 */
public class NewTask
{
	private final static String TASK_QUEUE_NAME = "task_queue";

	private static Connection connection;
	private static Channel channel;

	public static void main(String[] args)
	{
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("localhost");
		factory.setPort(5682);

		try
		{
			connection = factory.newConnection();
			channel = connection.createChannel();

			channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
			String message = "";

			while (true)
			{
				Thread.sleep(1000);
				message = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss") + " " + getMessage(args);
				channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN,
						message.getBytes("UTF-8"));
				System.out.println(" [x] Sent '" + message + "'");
			}

		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TimeoutException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally
		{
			try
			{
				channel.close();
				connection.close();
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (TimeoutException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static String getMessage(String[] strings)
	{
		if (strings.length < 1)
		{
			return "Hello World!";
		} else
		{
			return String.join(" ", strings);
		}
	}
}
